package com.xyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xyy.entity.Activity;
import com.xyy.entity.Admin;
import com.xyy.enums.ActivityStatus;
import com.xyy.dto.ActivityWithAdminDTO;
import com.xyy.mapper.ActivityMapper;
import com.xyy.mapper.AdminMapper;
import com.xyy.service.ActivityService;
import com.xyy.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 活动Service实现类
 */
@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {
    
    @Autowired
    private ActivityMapper activityMapper;
    
    @Autowired
    private AdminMapper adminMapper;
    
    @Autowired
    private FileService fileService;
    
    @Override
    public Activity createActivity(Activity createDTO, Long adminId) {
        // 验证时间逻辑
        if (createDTO.getStartTime().isAfter(createDTO.getEndTime())) {
            throw new RuntimeException("开始时间不能晚于结束时间");
        }
        
        // 检查管理员级别
        Admin admin = adminMapper.selectById(adminId);
        if (admin == null) {
            throw new RuntimeException("管理员不存在");
        }
        
        Activity activity = new Activity();
        BeanUtils.copyProperties(createDTO, activity);
        activity.setAdminId(adminId);
        
        // 根据管理员级别设置初始状态
        if (admin.getLevel() == 2) {
            // 超级管理员发布的活动直接通过审核
            activity.setStatus(ActivityStatus.APPROVED.getCode());
        } else {
            // 普通管理员发布的活动需要审核
            activity.setStatus(ActivityStatus.PENDING_AUDIT.getCode());
        }
        
        // createdAt和updatedAt由MyBatis-Plus自动填充
        activityMapper.insert(activity);
        return activity;
    }
    
    @Override
    public boolean deleteActivity(Long activityId, Long adminId) {
        // 检查活动是否存在且属于当前管理员
        Activity activity = getActivityByIdAndAdminId(activityId, adminId);
        if (activity == null) {
            return false;
        }
        
        return activityMapper.deleteById(activityId) > 0;
    }
    
    @Override
    public Activity updateActivity(Activity activity, Long adminId) {
        // 检查活动是否存在且属于当前管理员
        Activity existingActivity = getActivityByIdAndAdminId(activity.getId(), adminId);
        if (existingActivity == null) {
            throw new RuntimeException("活动不存在或无权限修改");
        }
        
        // 验证时间逻辑
        if (activity.getStartTime() != null && activity.getEndTime() != null) {
            if (activity.getStartTime().isAfter(activity.getEndTime())) {
                throw new RuntimeException("开始时间不能晚于结束时间");
            }
        }
        
        // updatedAt由MyBatis-Plus自动填充
        activityMapper.updateById(activity);
        return getActivityById(activity.getId());
    }
    
    @Override
    public List<Activity> getActivityList() {
        // 只返回已通过审核的活动
        return getApprovedActivities();
    }
    
    @Override
    public List<ActivityWithAdminDTO> getActivityListWithAdmin() {
        // 只返回已通过审核的活动
        return getApprovedActivitiesWithAdmin();
    }
    
    @Override
    public Activity getActivityById(Long activityId) {
        return activityMapper.selectById(activityId);
    }
    
    @Override
    public List<Activity> getActivityListByAdminId(Long adminId) {
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_id", adminId);
        queryWrapper.orderByDesc("created_at");
        
        List<Activity> activities = activityMapper.selectList(queryWrapper);
        
        // 为每个活动计算当前状态
        LocalDateTime now = LocalDateTime.now();
        for (Activity activity : activities) {
            activity.setStatus(calculateActivityStatus(activity.getStartTime(), activity.getEndTime()));
        }
        
        return activities;
    }
    
    @Override
    public String uploadCover(Long activityId, Long adminId, String filename, byte[] fileBytes) throws IOException {
        // 检查活动是否存在且属于当前管理员
        Activity activity = getActivityByIdAndAdminId(activityId, adminId);
        if (activity == null) {
            throw new RuntimeException("活动不存在或无权限修改");
        }
        
        // 上传文件并返回文件路径
        String coverPath = fileService.uploadFile(fileBytes, filename, "cover");
        
        // 更新活动封面
        updateActivityCover(activityId, adminId, coverPath);
        
        return coverPath;
    }
    
    @Override
    public void updateActivityCover(Long activityId, Long adminId, String coverPath) {
        // 检查活动是否存在且属于当前管理员
        Activity activity = getActivityByIdAndAdminId(activityId, adminId);
        if (activity == null) {
            throw new RuntimeException("活动不存在或无权限修改");
        }
        
        LambdaUpdateWrapper<Activity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Activity::getId, activityId)
                    .eq(Activity::getAdminId, adminId)
                    .set(Activity::getCover, coverPath);
        
        activityMapper.update(null, updateWrapper);
        
        log.info("活动封面更新成功: activityId={}, adminId={}, coverPath={}", activityId, adminId, coverPath);
    }
    
    @Override
    public String getActivityCoverPath(Long activityId) {
        try {
            Activity activity = activityMapper.selectById(activityId);
            if (activity == null || activity.getCover() == null || activity.getCover().isEmpty()) {
                return null;
            }
            
            return activity.getCover();
            
        } catch (Exception e) {
            log.error("获取活动封面文件路径失败: activityId={}", activityId, e);
            return null;
        }
    }
    
    @Override
    public String calculateActivityStatus(LocalDateTime startTime, LocalDateTime endTime) {
        LocalDateTime now = LocalDateTime.now();
        
        if (now.isBefore(startTime)) {
            return "UPCOMING"; // 即将开始
        } else if (now.isAfter(endTime)) {
            return "ENDED"; // 已结束
        } else {
            return "ONGOING"; // 进行中
        }
    }

    @Override
    public List<Activity> getActivityListByAdminRealName(String adminRealName) {
        // 先根据真实姓名查询管理员ID
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("real_name", adminRealName);
        adminQueryWrapper.eq("level", 1); // 只查询普通管理员
        
        Admin admin = adminMapper.selectOne(adminQueryWrapper);
        if (admin == null) {
            return new ArrayList<>();
        }
        
        // 根据管理员ID查询活动列表
        QueryWrapper<Activity> activityQueryWrapper = new QueryWrapper<>();
        activityQueryWrapper.eq("admin_id", admin.getId());
        activityQueryWrapper.orderByDesc("created_at");
        
        List<Activity> activities = activityMapper.selectList(activityQueryWrapper);
        
        // 为每个活动计算当前状态
        LocalDateTime now = LocalDateTime.now();
        for (Activity activity : activities) {
            activity.setStatus(calculateActivityStatus(activity.getStartTime(), activity.getEndTime()));
        }
        
        return activities;
    }
    
    @Override
    public org.springframework.core.io.Resource getActivityCover(String filename) {
        try {
            // 这里需要根据FileService的实际实现来调用正确的方法
            // 暂时返回null，因为FileService可能没有getFile方法
            log.warn("getActivityCover方法暂未实现，需要根据FileService的实际接口调整");
            return null;
        } catch (Exception e) {
            log.error("获取活动封面文件失败: filename={}", filename, e);
            return null;
        }
    }
    
    /**
     * 根据ID和管理员ID获取活动
     * @param activityId 活动ID
     * @param adminId 管理员ID
     * @return 活动
     */
    private Activity getActivityByIdAndAdminId(Long activityId, Long adminId) {
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", activityId);
        queryWrapper.eq("admin_id", adminId);
        
        return activityMapper.selectOne(queryWrapper);
    }
    
    @Override
    public boolean auditActivity(Long activityId, Long adminId, boolean approved, String auditComment) {
        // 检查管理员是否为超级管理员
        Admin admin = adminMapper.selectById(adminId);
        if (admin == null || admin.getLevel() != 2) {
            throw new RuntimeException("只有超级管理员才能审核活动");
        }
        
        // 检查活动是否存在
        Activity activity = activityMapper.selectById(activityId);
        if (activity == null) {
            throw new RuntimeException("活动不存在");
        }
        
        // 检查活动状态是否为待审核
        if (!ActivityStatus.PENDING_AUDIT.getCode().equals(activity.getStatus())) {
            throw new RuntimeException("只能审核待审核状态的活动");
        }
        
        // 更新活动状态
        String newStatus = approved ? ActivityStatus.APPROVED.getCode() : ActivityStatus.REJECTED.getCode();
        
        LambdaUpdateWrapper<Activity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Activity::getId, activityId)
                    .set(Activity::getStatus, newStatus);
        
        int result = activityMapper.update(null, updateWrapper);
        
        if (result > 0) {
            log.info("活动审核成功: activityId={}, adminId={}, approved={}, comment={}", 
                    activityId, adminId, approved, auditComment);
            return true;
        } else {
            log.error("活动审核失败: activityId={}, adminId={}", activityId, adminId);
            return false;
        }
    }
    
    @Override
    public List<Activity> getPendingAuditActivities() {
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", ActivityStatus.PENDING_AUDIT.getCode());
        queryWrapper.orderByDesc("created_at");
        
        List<Activity> activities = activityMapper.selectList(queryWrapper);
        
        // 为每个活动添加管理员信息
        for (Activity activity : activities) {
            if (activity.getAdminId() != null) {
                Admin admin = adminMapper.selectById(activity.getAdminId());
                if (admin != null) {
                    // 使用反射设置管理员名称字段
                    try {
                        activity.getClass().getDeclaredField("adminName").setAccessible(true);
                        activity.getClass().getDeclaredField("adminName").set(activity, admin.getRealName());
                    } catch (Exception e) {
                        log.warn("无法设置管理员名称字段: {}", e.getMessage());
                    }
                }
            }
        }
        
        return activities;
    }
    
    @Override
    public List<Activity> getApprovedActivities() {
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", ActivityStatus.APPROVED.getCode());
        queryWrapper.orderByDesc("created_at");
        
        List<Activity> activities = activityMapper.selectList(queryWrapper);
        
        // 为每个活动计算当前状态并添加管理员信息
        for (Activity activity : activities) {
            // 计算时间状态
            activity.setStatus(calculateActivityStatus(activity.getStartTime(), activity.getEndTime()));
            
            // 获取管理员信息
            if (activity.getAdminId() != null) {
                Admin admin = adminMapper.selectById(activity.getAdminId());
                if (admin != null) {
                    // 使用反射设置管理员名称字段
                    try {
                        activity.getClass().getDeclaredField("adminName").setAccessible(true);
                        activity.getClass().getDeclaredField("adminName").set(activity, admin.getRealName());
                    } catch (Exception e) {
                        log.warn("无法设置管理员名称字段: {}", e.getMessage());
                    }
                }
            }
        }
        
        return activities;
    }
    
    @Override
    public List<ActivityWithAdminDTO> getApprovedActivitiesWithAdmin() {
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", ActivityStatus.APPROVED.getCode());
        queryWrapper.orderByDesc("created_at");
        
        List<Activity> activities = activityMapper.selectList(queryWrapper);
        List<ActivityWithAdminDTO> result = new ArrayList<>();
        
        // 为每个活动计算当前状态并添加管理员信息
        for (Activity activity : activities) {
            ActivityWithAdminDTO dto = new ActivityWithAdminDTO();
            
            // 复制活动信息
            dto.setId(activity.getId());
            dto.setName(activity.getName());
            dto.setCover(activity.getCover());
            dto.setDescription(activity.getDescription());
            dto.setLocation(activity.getLocation());
            dto.setStartTime(activity.getStartTime());
            dto.setEndTime(activity.getEndTime());
            dto.setCreatedAt(activity.getCreatedAt());
            dto.setUpdatedAt(activity.getUpdatedAt());
            dto.setPoints(activity.getPoints());
            dto.setAdminId(activity.getAdminId());
            
            // 计算活动状态
            dto.setStatus(calculateActivityStatus(activity.getStartTime(), activity.getEndTime()));
            
            // 获取管理员信息
            if (activity.getAdminId() != null) {
                Admin admin = adminMapper.selectById(activity.getAdminId());
                if (admin != null) {
                    dto.setAdminRealName(admin.getRealName());
                    dto.setAdminUsername(admin.getUsername());
                    dto.setAdminPhone(admin.getPhone());
                }
            }
            
            result.add(dto);
        }
        
        return result;
    }
} 